package com.emergency.db.service.impl;
//数据字典


import com.emergency.common.entity.TreeNode;
import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import com.emergency.db.dao.DictionaryDao;
import com.emergency.db.domain.Dictionary;
import com.emergency.db.service.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.Serializable;
import java.util.*;

@Service
public class DicServiceImpl implements DictionaryService {

    @Autowired
    private DictionaryDao dictionaryDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedisTemplate redisTemplate;

    //保存
    public Long save(Dictionary dictionary) {
        //删除redis缓存中数据信息
        redisTemplate.delete("dict:key");

        if (CommonUtils.isNullOrEmpty(dictionary.getId())) {
            dictionary.setId(idWorker.nextId());
            dictionary.setCreateTime(new Date());
        }
        //保存字典信息
        dictionaryDao.save(dictionary);
        return dictionary.getId();
    }

    //查询单项
    public Dictionary findById(Long id) {
        return dictionaryDao.findById(id).get();
    }



    //删除
    public void delete(Long id) {
        redisTemplate.delete("dict:key");
        dictionaryDao.deleteById(id);
    }

    //查询字典全部信息
    @Override
    public List<Dictionary> findALL() {
        return dictionaryDao.find();
    }

    //树形结构

    public List<TreeNode> getTreeData() {
        //先从缓存中获取，如果没有，则读取数据库存入缓存。
        List<Dictionary> dictionaryList = redisTemplate.opsForList().range("dict:key", 0, -1);
        if (CommonUtils.isNullOrEmpty(dictionaryList)) {
            dictionaryList = dictionaryDao.find();
            redisTemplate.opsForList().leftPushAll("dict:key", dictionaryList);
        }

        Map<Long, TreeNode> nodelist = new LinkedHashMap<Long, TreeNode>();
        List<TreeNode> treelist = new ArrayList<TreeNode>();
        for (Dictionary dictionary : dictionaryList) {
            //构造树节点
            TreeNode node = new TreeNode();
            node.setId(dictionary.getId());
            node.setParentId(dictionary.getParent());
            node.setCode(dictionary.getCode());
            node.setCodeText(dictionary.getCodeText());
            nodelist.put(node.getId(), node);
        }
        //遍历map
        for (Long id : nodelist.keySet()) {
            TreeNode node = nodelist.get(id);
            //如果没有父节点，表示该节点为父节点，直接添加
            if (CommonUtils.isNullOrEmpty(node.getParentId())) {
                treelist.add(node);
            } else {
                //有父节点，它的孩子节点为空，则创建孩子节点
                if (nodelist.get(node.getParentId()).getChildren() == null)
                    nodelist.get(node.getParentId()).setChildren(new ArrayList<TreeNode>());
                nodelist.get(node.getParentId()).getChildren().add(node);
            }
        }
        return treelist;
    }


    //分页查询
    @Override
    public Page<Dictionary> findList(Map searchMap, int page, int size) {
        Specification<Dictionary> specification = createSpecification(searchMap);
        Sort sort = Sort.by(Sort.Direction.ASC, "sortNum");
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        return dictionaryDao.findAll(specification, pageRequest);
    }


    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Dictionary> createSpecification(Map searchMap) {
        return new Specification<Dictionary>() {

            @Override
            public Predicate toPredicate(Root<Dictionary> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                // 字典类型
                if (searchMap.get("type") != null && !"".equals(searchMap.get("type"))) {
                    predicateList.add(criteriaBuilder.like(root.get("type").as(String.class), "%" + (String) searchMap.get("type") + "%"));
                }
                // 枚举字段名
                if (searchMap.get("value") != null && !"".equals(searchMap.get("value"))) {
                    predicateList.add(criteriaBuilder.like(root.get("value").as(String.class), "%" + (String) searchMap.get("value") + "%"));
                }
                // 编码值
                if (searchMap.get("code") != null && !"".equals(searchMap.get("code"))) {
                    predicateList.add(criteriaBuilder.equal(root.get("code").as(String.class), (String) searchMap.get("code")));
                }
                // 编码文本
                if (searchMap.get("codeText") != null && !"".equals(searchMap.get("codeText"))) {
                    predicateList.add(criteriaBuilder.like(root.get("codeText").as(String.class), "%" + (String) searchMap.get("codeText") + "%"));
                }
                // 是否启用
                if (searchMap.get("isEnable") != null && !"".equals(searchMap.get("isEnable"))) {
                    predicateList.add(criteriaBuilder.like(root.get("isEnable").as(String.class), (String) searchMap.get("isEnable")));
                }

                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }
}
